package com.diipo.weibo;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.LinkedList;
import com.diipo.weibo.entity.HomeAll;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import com.diipo.weibo.utils.HttpUtils;
import com.diipo.weibo.utils.JsonUtils;
import com.google.gson.reflect.TypeToken;
import com.diipo.weibo.adapter.WeiboItemAdapter;

public class Home extends Activity{
	

	private String TAG = Home.class.getSimpleName();
	private ListView weiboList;
	private String url_activity = "/api/statuses/activity.json?api_key=";
	private LinkedList<HomeAll> list = new LinkedList<HomeAll>();
	LinkedList<HomeAll> list2 = new LinkedList<HomeAll>();
	private Button mCreateWeibo;
	private Button mRefreshWeibo;
	private TextView mMore;
	private Context mctx;
	private boolean mIsmore = false;
	private Handler handler = new Handler();
	private int moreCount = 0;
	private boolean mIsRefresh = false;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// Hide title 
        requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.home);
		mctx = this;
//		ConfigInfo.setInstanceContext(this);
		LinearLayout v = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.list_footer, null);
		mMore = (TextView)v.findViewById(R.id.footer_more);
		mMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e(TAG, " add button was clicked,add more data from the server pos = " + weiboList.getCount());
				String before = null;
				try{
					before = list.get(list.size()-1).getCreated_time();
				}catch(NullPointerException e){
					e.printStackTrace();
				}
				Log.e(TAG, " add more data from the server last before time = " + before);
				mIsmore = true;
				new AsyncDataLoader(asyncRemoteCallback,mctx,url_activity,"","",before).execute();
			}
		});
		mRefreshWeibo = (Button) findViewById(R.id.titlebar_refresh);
		mRefreshWeibo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e(TAG, " refresh data from server,get the newest data .........");
				mIsRefresh = true;
				//disable the mRefreshWeibo button
				Log.e(TAG, " onClick() called ,pyb mRefreshWeibo.setEnabled(false).");
				mRefreshWeibo.setEnabled(false);
				//update the home UI
				new AsyncDataLoader(asyncRemoteCallback,mctx,url_activity,"","","").execute();
				
			}
		});
		mCreateWeibo = (Button) findViewById(R.id.titlebar_createWeibo);
		mCreateWeibo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(Home.this,CreateWeiBoActivity.class);
				i.putExtra(ConfigInfo.COMM.SEND_TYPE,ConfigInfo.COMM.WEIBO_MSG);
				startActivityForResult(i, ConfigInfo.CALLBACK_CREATE_WEIBO);
			}
		});
		weiboList = (ListView) findViewById(R.id.home_weiboList);
		weiboList.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if(scrollState == SCROLL_STATE_FLING){
					Log.e(TAG, "pyb mRefreshWeibo.setEnabled(false).");
					mRefreshWeibo.setEnabled(false);
				}else if(scrollState == SCROLL_STATE_IDLE){
//					handler.postDelayed(new Runnable() {
//						@Override
//						public void run() {
//							Log.e(TAG, " mRefreshWeibo.setEnabled(true).");
//							mRefreshWeibo.setEnabled(true);
//						}
//					},2000);
					Log.e(TAG, " pyb mRefreshWeibo.setEnabled(true).");
					mRefreshWeibo.setEnabled(true);
				}else if(scrollState == SCROLL_STATE_TOUCH_SCROLL){
					mRefreshWeibo.setEnabled(false);
				}else{
					
				}
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
		Log.e(TAG, " Home onCreate() called ...");
		new AsyncDataLoader(asyncRemoteCallback,this,url_activity,"","","").execute();
		weiboList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.e(TAG, " weiboList setOnItemClickListener() called ... position = " + position);
				Intent intent = new Intent(Home.this,WeiboDetailsActivity.class);
				intent.putExtra(ConfigInfo.COMM.MSG_ID, list.get(position).getId());
				intent.putExtra(ConfigInfo.COMM.ROOT_ID, list.get(position).getRoot_id());
				intent.putExtra(ConfigInfo.COMM.APP_TYPE, list.get(position).getApp_type());
				intent.putExtra(ConfigInfo.COMM.ITEM_TYPE, "");  
				startActivity(intent);
			}
		});
		weiboList.addFooterView(v);
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.e(TAG, " onActivityResult() called  resultCode = " + resultCode + " requestCode = " + requestCode);
		Log.e(TAG, " onActivityResult() called  ret intent = " + data.getStringExtra(ConfigInfo.COMM.SEND_TYPE));
		String str = data.getStringExtra(ConfigInfo.COMM.SEND_TYPE);
		Log.e(TAG, " onActivityResult() called,str = " + str);
		if(ConfigInfo.CALLBACK_CREATE_WEIBO == requestCode){
			if(str.equals(ConfigInfo.COMM.WEIBO_MSG)){
				Log.e(TAG, " onActivityResult() called,create weibo success,weather clear the list array here??????");
				list.clear();
				//update the home UI
				new AsyncDataLoader(asyncRemoteCallback,this,url_activity,"","","").execute();
			}
		}
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e(TAG, " Home onResume() called ...");
		if(ConfigInfo.COMM.UPDATE_DATA){
			ConfigInfo.COMM.UPDATE_DATA = false;//reset this value
//			list.clear();
			//update the home UI
			new AsyncDataLoader(asyncRemoteCallback,this,url_activity,"","","").execute();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e(TAG, " Home onDestroy() called ...");
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ConfirmExit();// 按了返回键，但已经不能返回，则执行退出确认
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void ConfirmExit() {// 退出确认
		AlertDialog.Builder dialog = new AlertDialog.Builder(Home.this);
		dialog.setTitle(mctx.getString(R.string.exit));
		dialog.setMessage(mctx.getString(R.string.is_exit_weibo));
		dialog.setPositiveButton(mctx.getString(R.string.btn_ok), new DialogInterface.OnClickListener() {// 退出按钮
					@Override
					public void onClick(DialogInterface dialog, int i) {
						// TODO Auto-generated method stub
						Home.this.finish();// 关闭activity
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
		dialog.setNegativeButton(mctx.getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// 不退出不用执行任何操作
			}
		});
		dialog.show();// 显示对话框
	}
	
	/**
	 * 异步加载服务器上的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncRemoteCallback = new AsyncDataLoader.Callback() {
		
		private SharedPreferences mPrefs;
	
		private Type listType = new TypeToken<LinkedList<HomeAll>>() {}.getType();
		private String result;
		@Override
		public void onStart(String address,String more) {
			    
				mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
				StringBuffer url = new StringBuffer();
				url.append(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS,mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
				url.append(address);
				url.append(ConfigInfo.COMM.APY_KEY);
				if (list.size()>=20 && !mIsRefresh) {
					url.append("&time=");
					try {
						more = java.net.URLEncoder.encode(more,"utf-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					url.append(more);
				}
				String username = mPrefs.getString(ConfigInfo.PREF_USERNAME,"");
				String passwd = mPrefs.getString(ConfigInfo.PREF_PASSWORD,"");
				
				//需要做出判断，username 或者 passwd为非法值
				
				result = HttpUtils.doPost(url.toString(), username,passwd, null);
				Log.e(TAG,"url address = "+url);
//				Log.e(""," username  = "+username);
//				Log.e(""," passwd  = "+passwd);
				Log.e(TAG," activity result =  " + result);
				if (result != ConfigInfo.HTTPRETURN.COMMHTTPERRORS 
						&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_400 
						&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_401 
						&& result != ConfigInfo.HTTPRETURN.HTTPERROR 
						&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404 ) {
					//大于20加载更多
					if (list.size()>=20 && !mIsRefresh) {
						list2 = JsonUtils.parseUserFromJsons(result, listType);
						moreCount = list2.size();
						Iterator<HomeAll> iterator = list2.iterator();
						Log.e(TAG, " ===================    Home list2 size = " + list2.size());
						
						while (iterator.hasNext()) {
							list.add(iterator.next());
						}
						// hide the more btn data from the server
						if(list2.size() < 20){
							//hanlder在主线程做UI操作
							handler.post(new Runnable() {
								@Override
								public void run() {
									mMore.setVisibility(View.GONE);
								}
							});
						}
						//clear the list2 here
						list2.clear();
					}else {	//初次加载
						list.clear();
						Log.e(TAG, " clear the list array here....");
						list = JsonUtils.parseUserFromJsons(result, listType);
						if(list.size()< 20){
							handler.post(new Runnable() {
								@Override
								public void run() {
									mMore.setVisibility(View.GONE);
								}
							});
						}else{
							handler.post(new Runnable() {
								@Override
								public void run() {
									mMore.setVisibility(View.VISIBLE);
								}
							});
						}
						Log.e(TAG, " ===================    Home list size = " + list.size());
						
					}
			} else if (result == ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404) {
				// get no data from the server
				handler.post(new Runnable() {
					@Override
					public void run() {
						mMore.setVisibility(View.GONE);
					}
				});
			} else {
				// network error here
					handler.post(new Runnable() {
						@Override
						public void run() {
							mMore.setVisibility(View.GONE);
							Toast.makeText(Home.this, result, Toast.LENGTH_LONG).show();
						}
					});
				}
		}

		@Override
		public void onPrepare() {
		}

		@Override
		public void onFinish() {
			//if(!weiboList.isFocusable()){
			mIsRefresh = false;
			if(list.size()<1){
				Log.e(TAG, " no new data from the server===========================================  ");
//				Toast.makeText(Home.this, result, Toast.LENGTH_LONG).show();
				WeiboItemAdapter adapter = new WeiboItemAdapter(list,Home.this);
				weiboList.setAdapter(adapter);
				mRefreshWeibo.setEnabled(true);
				return;
			}
			WeiboItemAdapter adapter = new WeiboItemAdapter(list,Home.this);
			weiboList.setAdapter(adapter);

			if(mIsmore){
				weiboList.setSelection(list.size()-1-moreCount);
				mIsmore = false;
			}else{
				
			}
			mRefreshWeibo.setEnabled(true);
		}

		@Override
		public void onStart(String address, String arg1, String arg2) {
			// TODO Auto-generated method stub
			
		}
	};
}
